package com.ruoyi.web.controller.tool;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * DES加密和解密工具类
 */
public class DesUtil {
    private static final String ALGORITHM = "DES/CBC/PKCS5Padding"; // 使用PKCS5Padding和CBC模式

    // 加密
    public static String encrypt(String key, String data) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "DES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);

        // 这里使用 IV，需要是8字节
        byte[] iv = new byte[8]; // 可以使用更复杂的IV
        IvParameterSpec ivParams = new IvParameterSpec(iv);

        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParams);
        byte[] encryptedData = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 解密
    public static String decrypt(String key, String encryptedData) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "DES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);

        byte[] iv = new byte[8]; // 要与加密时使用的IV相同
        IvParameterSpec ivParams = new IvParameterSpec(iv);

        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParams);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] originalData = cipher.doFinal(decodedData);
        return new String(originalData, "UTF-8");
    }
    public static void main(String[] args) {
        try {
            String key = "a1b2c3d4"; // 密钥必须是8字节
            String data = "Hello, World!";
            String encryptedData = encrypt(key, data);
            String decryptedData = decrypt(key, encryptedData);

            System.out.println("原始数据: " + data);
            System.out.println("加密数据: " + encryptedData);
            System.out.println("解密数据: " + decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
